layui.use(['element', 'layer'], function () {
    var element = layui.element;
    var layer = layui.layer;

    window.homeUrl = null;//菜单第一个链接
    $.ajax({
        url: '/sys/menu/getUserMenuList',
        type: 'get',
        success: function (result) {
            if (result.success && result.data && result.data.length > 0) {
                if (result.data[0].subList) {
                    homeUrl = result.data[0].subList[0].url;
                } else {
                    homeUrl = result.data[0].url;
                }
                //渲染页面
                smartAui.renderHtml({
                    targetId: 'SM-menu',
                    template: '/views/common/template/menu.html',
                    htmlData: result,
                    callBack: function () {
                        element.render();
                        //如果由index.html首次进入页面,顶掉页面url历史记录
                        var title = document.title;
                        var hash = (location.hash == "" || location.hash.length === 1) ? homeUrl : location.hash.substring(1);
                        var url = location.protocol + '//' + location.host + location.pathname + location.search + '#' + hash;
                        history.replaceState(null, title, url);
                        // replaceState事件无法手动触发
                        hashchange();
                    }
                })
            }
        }
    });

    //hash监听，用于回退及点击菜单
    window.addEventListener('hashchange', hashchange, false);

    //点击修改密码
    $('#changePassword').click(function () {
        var passIndex = layer.open({
            type: 1,
            title: '密码修改',
            content: $("#edit_pwd"),
            area: ['400px', '300px'],
            shade: 0.6, //遮罩透明度
            anim: 1, //0-6的动画形式，-1不开启
            btn: ['确认修改', '取消'],
            yes: function () {
                var nowpassword = $('#SM-nowpassword').val();
                var password = $('#SM-password').val();
                var repassword = $('#SM-repassword').val();
                if (nowpassword == '') {
                    layer.msg('请输入初始密码');
                } else if (password == '') {
                    layer.msg('请输入新密码');
                } else if (repassword == '') {
                    layer.msg('请确认新密码');
                } else if (password != repassword) {
                    layer.msg('两次密码不一致');
                } else {
                    $.ajax({
                        url: '/user/updatepwd',
                        data: {
                            password: nowpassword,
                            newPassword: repassword
                        },
                        success: function (result) {
                            if (result.success) {
                                layer.msg('修改密码成功3s后自动跳转到登录页');
                                localStorage.clear('password');
                                setTimeout(function () {
                                    window.location.href = '/views/login.html';
                                }, 3000)

                            } else {
                                layer.msg(result.msg || "操作异常");
                            }
                        },
                        error: function () {
                            layer.msg("操作异常");
                        }
                    });
                }
            },
            end: function () {
                $('#nowpassword').val('');
                $('#password').val('');
                $('#repassword').val('');
            },
        })
    });

    $(document).on("click", "a[data-url]", function (e) {
        console.log("click");
        var $this = $(this);
        var hash = $this.attr("data-url");
        var iframeFlag=$(this).attr("data-iframe");
        if (hash) {
            if(iframeFlag==1){
                jumpByHash("iframe",{url:hash});
            }else{
                jumpByHash(hash);
            }
        }
    });

    var account=localStorage.getItem("account");
    var avatar=localStorage.getItem("avatar");
    account && $("#userName").text(account);
    if(avatar){
        var avatarEle=new Image();
        avatarEle.src=avatar;
        avatarEle.onload=function () {
            $("#userPhoto").attr("src", avatar);
        };
    }
    //获取当前公众号及其他公众号
    getCountStatus();

    // 切换删除账号
    $("#SM-account").on("click", "a[data-account]", function (e) {
        var $this = $(this);
        var id = $this.attr("data-id");
        var account = $this.attr("data-account");
        if ($(e.target).hasClass("delete")) {
            // 删除
            smartAui.confirm("确认删除此账号？", function () {
                smartAui.ajax({
                    url: '/account/delete',
                    data: {account: account},
                    success: function (result) {
                        if (result.success) {
                            layer.closeAll();
                            layer.msg("操作成功！");
                            getCountStatus();
                        } else {
                            layer.msg("操作失败！");
                        }
                    }
                });
            })
        } else {
            // 切换
            getCountStatus(id);
        }
    });

    // 退出
    $("#SM-exit").on("click", function () {
        $.ajax({
            url: '/user/logout',
            dataType: "json",
            success: function (result) {
                if (result.success) {
                    window.location.href = "/views/login.html";
                } else {
                    layer.msg("退出失败");
                }
            }
        })
    });

    // 弹出配色主题
    $("#SM-theme").click(function () {
        smartAui.getHtml(
            "/views/common/template/theme.html",
            function (html) {
                var index = layer.open({
                    title: false,
                    anim: -1,
                    type: 1,
                    area: ['300px', $(window).height() - 60 + "px"],
                    fixed: true,
                    closeBtn: 0,
                    shadeClose: true,
                    offset: 'rb',
                    content: html,
                    btn: 0,
                    success: function () {
                        $(".layadmin-setTheme-color").on("click", "li", function () {
                            var name = $(this).attr("data-theme");
                            $(this).addClass("layui-this")
                                .siblings(".layui-this").removeClass("layui-this");
                            $(".layui-layout-admin").attr("data-theme", name);
                            localStorage.setItem("SM-theme", name);
                            layer.close(index);
                        });
                    }
                })
            });
    });

    // 点击全屏与退出全屏
    $('a[layadmin-event="fullscreen"]').on('click', function (e) {
        var element = document.documentElement;
        if (!$('body').hasClass("full-screen")) {
            $('body').addClass("full-screen");
            smartAui.fullscreen(true);
            $(this).children(".layui-icon")
                .removeClass("layui-icon-screen-full")
                .addClass("layui-icon-screen-restore");
        } else {
            $('body').removeClass("full-screen");
            $(this).children(".layui-icon")
                .removeClass("layui-icon-screen-restore")
                .addClass("layui-icon-screen-full");
            smartAui.fullscreen(false);
        }
    });

    // 菜单收起
    $("#SM-flexible").click(function () {
        var $con = $(".layui-layout-admin");
        if (!$con.hasClass("layadmin-side-shrink")) {
            $("#SM-menu .layui-nav-itemed").removeClass("layui-nav-itemed");
        }
        $con.toggleClass("layadmin-side-shrink");
        $(this).children("i").toggleClass("layui-icon-shrink-right")
            .toggleClass("layui-icon-spread-left");
    });

    // 修改头像
    $("#userPhoto").click(function () {
        smartAui.dialog({
            title: '添加',
            template: '/views/common/template/avatar.html',
            saveUrl: '/user/update',
            width: 500,
            height: 300,
            beforeSubmit:function (data) {
                if(!data.avatar){
                    layer.msg("请上传头像！");
                    return false;
                }
                return true;
            },
            submited:function (res) {
                smartAui.ajax({
                    url: '/user/info',
                    type:"get",
                    success: function (result) {
                        if (result.success && result.data) {
                            var avatar=result.data.avatar;
                            if(avatar){
                                var avatarEle=new Image();
                                avatarEle.src=avatar;
                                avatarEle.onload=function () {
                                    localStorage.setItem('avatar', avatar);
                                    $("#userPhoto").attr("src", avatar);
                                };
                            }
                        }
                    },
                });
            }
        });
    });


    // 主题回显
    var theme = localStorage.getItem("SM-theme");
    theme && $(".layui-layout-admin").attr("data-theme", theme);

    // 左右布局收起
    function toggleResize() {
        console.log("toggleResize");
        $("#SM-panelResize").parents(".panel").toggleClass("panel-close").removeAttr("style")
    }

    $(document).on("click", "#SM-panelResize", toggleResize);

    // 左右布局拖动
    var isResizing = false;
    var lastDownX = 0;
    $(document).on('mousedown', "#SM-panel-resize", function (e) {
        if ($(this).parents(".panel").hasClass("panel-close")) {
            return true;
        }
        isResizing = true;
        lastDownX = e.clientX;
    }).on('mousemove', function (e) {
        if (!isResizing) return true;
        var $container = $("#SM-panel-resize").parent();
        var width = e.clientX - $container.offset().left;
        // 判断左右拖动范围
        if (width < 100) {
            isResizing = false;
            return true;
        }
        $container.css('width', width);
    }).on('mouseup', function (e) {
        isResizing = false;
    });

    var _hmt = _hmt || [];
    (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?f07686635800b1dc0587d91cd81bf3b0";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s)
    })();
    (function () {
        var bp = document.createElement("script");
        var curProtocol = window.location.protocol.split(":")[0];
        if (curProtocol === "https") {
            bp.src = "https://zz.bdstatic.com/linksubmit/push.js"
        } else {
            bp.src = "http://push.zhanzhang.baidu.com/push.js"
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s)
    })();
});

//获取当前公众号及其他公众号
function getCountStatus(id) {
    $.ajax({
        url: '/account/listForPage',
        data: {id: id},
        success: function (result) {
            if (result.success) {
                if (id) {
                    location.reload();
                } else {
                    if (result.data) {
                        smartAui.renderHtml({
                            targetId: 'SM-account',
                            template: "/views/common/template/account-nav.html",
                            htmlData: result
                        });
                    }
                }
            }
        }
    });
}

/**
 * hashchange的回调函数，渲染右侧
 *
 * @author sayHi
 */
function hashchange() {
    var hash = (location.hash == "" || location.hash.length === 1) ? homeUrl : location.hash.substring(1);
    hash = hash.replace(/\[.*\]/, "");
    if(hash=="iframe"){
        var url=getHashParam().url;
        var temp='<div class="sm-iframe-wrap">'
            +'<iframe src="'+url+'" frameborder="0" class="sm-iframe"></iframe>'
            +'</div>';
        $("#SM-body").empty().html(template.render(temp,{}));
        hash=url;
    }else{
        var temp = "/views" + hash + ".html";
        // 清理ztree数据 important!
        $.fn.zTree && $.fn.zTree.destroy();
        smartAui.renderHtml({
            loading: true,
            targetId: 'SM-body',
            template: temp
        });
    }

    var $a = $(".sm-menu a[data-url='" + hash + "']");
    if ($a.length > 0) {
        $a.length > 1 && ($a = $a.eq(0));
        if($a.attr("data-level")=="3"){
            $a.parent("dd").addClass('layui-this').parents("dd").addClass('layui-nav-itemed');
        }else{
            $a.parent("dd").addClass('layui-this').siblings('.layui-this').removeClass('layui-this');
        }
    } else if (location.hash.length > 1) {
        var $alist = $(".sm-menu a[data-url]");
        var h = location.hash.substring(0, location.hash.lastIndexOf("/")).substring(1);
        !!(h) && $alist.each(function (i, v) {
            var $a = $(this);
            var url = $a.attr("data-url").substring(0, location.hash.lastIndexOf("/"));
            if (url.indexOf(h) == 0) {
                $a.parents('li').addClass('layui-nav-itemed').siblings('li').removeClass('layui-nav-itemed');
                $a.parent("dd").addClass('layui-this').siblings('.layui-this').removeClass('layui-this');
                return false;
            }
        })
    }
    layer.closeAll();
}

/**
 * 改变hash方式跳转
 *
 * @author sayHi
 */
function jumpByHash(hash, data) {
    if (data) {
        var str = "";
        for (var i in data) {
            str+=(i+"="+data[i]+"&");
        }
        hash=hash+"["+str.substring(0, str.length - 1)+"]";
    }
    if (location.hash == "#" + hash) {
        hashchange();
    } else {
        location.hash = hash;
    }
}

/**
 * 获取hash中的参数，hash=/aaa/aaa[a=1&b=2]
 *
 * @author sayHi
 */
function getHashParam() {
    var hash = location.hash;
    var param = hash.match(/\[(.*)\]/, "");
    if (!param) {
        return {};
    } else {
        var arr = param[1].split("&");
        var o = {};
        for (var i = 0; i < arr.length; i++) {
            var d = arr[i].split("=");
            d.length == 2 && (o[d[0]] = decodeURI(d[1]));
        }
        return o;
    }
}